package com.estore.network;

import com.estore.model.Product;
import com.estore.service.ProductService;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

public class EStoreServer {
    private ProductService productService;
    public EStoreServer() {
        this.productService = new ProductService(); // 初始化业务服务
    }
    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();
        server.startServer();
    }
    private void startServer() {
        int port = 8888;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器已启动，监听端口：" + port);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到客户端连接：" + clientSocket.getInetAddress());
                handleClient(clientSocket);
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败：" + e.getMessage());
        }
    }
    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())) {
            String request = (String) ois.readObject();
            System.out.println("收到请求：" + request);
            if ("GET_ALL_PRODUCTS".equals(request)) {
                Map<String, Product> productMap = productService.getAllProducts();
                List<Product> productList = new ArrayList<>(productMap.values());
                oos.writeObject(productList);
                oos.flush();
                System.out.println("已向客户端返回商品列表，共" + productList.size() + "件商品");
            } else {
                oos.writeObject("未知请求");
                oos.flush();
                System.out.println("客户端请求无效：" + request);
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("处理客户端请求异常：" + e.getMessage());
        } finally {
            try {
                clientSocket.close();
                System.out.println("客户端连接已关闭");
            } catch (IOException e) {
                System.err.println("关闭客户端连接失败：" + e.getMessage());
            }
        }
    }
}